package com;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import com.netflix.client.ClientException;
import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.niws.client.http.RestClient;

public class AsyncHystrixDemo extends HystrixCommand<String> {

	RestClient client = null;
	HttpRequest request = null;

	public AsyncHystrixDemo() {
		// 指定命令组的名字
		super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
	}

	private void initRestClient() {
		client = (RestClient) ClientFactory.getNamedClient("AsyncHystrix");
		try {
			request = HttpRequest.newBuilder().uri(new URI("/available"))
					.build();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		ConfigurationManager.getConfigInstance().setProperty(
				"AsyncHystrix.ribbon.listOfServers", "localhost:8080");
	}

	protected String run() {
		System.out.println("In run");

		HttpResponse response;
		String result = null;
		try {
			response = client.executeWithLoadBalancer(request);
			System.out.println("Status for URI:" + response.getRequestedURI()
					+ " is :" + response.getStatus());
			result = response.getEntity(String.class);
		} catch (ClientException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "Hystrix Demo,result is: " + result;
	}

	public static void main(String[] args) {

		AsyncHystrixDemo asyncDemo = new AsyncHystrixDemo();
		asyncDemo.initRestClient();

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		Future<String> future = asyncDemo.queue();
		String result = null;
		try {
			System.out.println("Start Async Call");
			result = future.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println("Call available function, result is:" + result);
	}
}
